package hc.bre.cmn;

import java.util.LinkedList;
import java.util.List;

public interface IDetailList<T extends IId> {
	List<T> getList();

	void setList(List<T> list);

	default T find(int id) {
		return findFrom(id, getList());
	}

	default List<T> routeOf(int id) {
		return routeFrom(id, getList());
	};

	@SuppressWarnings({ "rawtypes", "unchecked" })
	static <T extends IId> T findFrom(int id, List<T> lst) {
		if (lst == null)
			return null;

		for (T it : lst) {
			if (ITreeNode.class.isAssignableFrom(it.getClass())) {
				ITreeNode itt = (ITreeNode) it;
				itt = itt.find(id);
				if (itt != null)
					return (T) itt;

			} else if (it.getId() == id) {
				return it;
			}
		}

		return null;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	static <T extends IId> List<T> routeFrom(int id, List<T> list) {
		LinkedList<T> stack = new LinkedList<T>();

		if (list == null || list.size() == 0)
			return stack;

		if (ITreeNode.class.isAssignableFrom(list.get(0).getClass())) {
			ITreeNode.routeFrom(id, (List<ITreeNode>) list, (LinkedList<ITreeNode>) stack);
		} else {
			for (T it : list) {
				if (it.getId() == id) {
					stack.addLast(it);
					break;
				}
			}
		}

		return stack;
	}
}
